﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Text;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell.Interop;

namespace PowerGuiVsx.Module
{
    [Cmdlet(VerbsDiagnostic.Debug, "ProcessEx")]
    public class DebugProcessCommand : PowerGuiVsxCommand
    {
        [Parameter(Mandatory=true, ParameterSetName="Process", ValueFromPipeline=true)]
        public System.Diagnostics.Process Process { get; set; }
        [Parameter(Mandatory = true, ParameterSetName = "Id", ValueFromPipeline=true)]
        public int Id { get; set; }
        [Parameter(ParameterSetName = "Process")]
        [Parameter(ParameterSetName = "Id")]
        public string ComputerName { get; set; }

        protected override void ProcessRecord()
        {
            int id = ParameterSetName == "Process" ? Process.Id : Id;

            if (String.IsNullOrEmpty(ComputerName))
            {
                AttachToProcess(id);
            }
            else
            {
                AttachToProcess(id, ComputerName);
            }
        }

        public static void AttachToProcess(int processId)
        {
            var dte = (DTE)Package.GetService(typeof(DTE));

            foreach (EnvDTE.Process process in dte.Debugger.LocalProcesses)
            {

                if (process.ProcessID == processId)
                {
                    process.Attach();

                    dte.Debugger.CurrentProcess = process;

                }

            }

        }

        public static void AttachToProcess(int processId, string computerName)
        {
            var dte = (DTE)Package.GetService(typeof(DTE));

            Debugger2 db = (Debugger2)dte.Debugger;
            Transport trans = db.Transports.Item("Default");
            foreach (Process2 process in db.GetProcesses(trans, computerName))
            {
                if (process.ProcessID == processId)
                {
                    process.Attach2();
                    dte.Debugger.CurrentProcess = process;
                }
            }
        }
    }
}
